package com.example.jam.musicplayer;

import android.Manifest;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.AlteredCharSequence;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jam.musicplayer.data.Music;
import com.example.jam.musicplayer.data.MusicList;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PropertyResourceBundle;
import java.util.Timer;
import java.util.TimerTask;

public class musicplayer extends AppCompatActivity implements GestureDetector.OnGestureListener{

    private static final int PERMISSION_REQUESTCODE = 1;

    // 显示组件
    private ImageButton imgBtn_Previous;
    private ImageButton imgBtn_PlayOrPause;
    private ImageButton imgBtn_Stop;
    private ImageButton imgBtn_Next;
    private ListView list;
    private RelativeLayout root_Layout;
    private TextView playingmsm1;
    private TextView playingmsm2;
    private TextView text_Current;
    private TextView text_Duration;
    private SeekBar seekBar;
    private TextView textView;
    private Handler seekBarHandler;
    private int duration;
    private int time;
    private static final int PROGRESS_INCREASE = 0;
    private static final int PROGRESS_PAUSE = 1;
    private static final int PROGRESS_RESET = 3;
    private static final int MODE_LIST_SEQUENCE = 0;
    private static final int MODE_SINGLE_CYCLE = 1;
    private static final int MODE_LIST_CYCLE = 2;
    private static final int MODE_RANDOM_PLAY=3;
    private int playmode;
    private static int STR=0;

    //音量控制
    private SeekBar seekBar_vol;
    private static boolean ExitFlag = false;

    //睡眠模式
    private ImageView iv_sleep;
    private Timer timer_sleep;
    private static final boolean NOTSLEEP = false;
    private static final boolean ISSLEEP = true;

    //默认睡眠时间
    private int sleepminute = 20;
    //标记是否打开睡眠模式
    private static boolean sleepmode;
    //手势
    private GestureDetector gestureDetector;
    private boolean gesturefree = true;

    //歌曲列表对象
    private ArrayList<Music> musicArrayList;

    // 当前歌曲的序号，下标从0开始
    private int number = 0;

    //播放状态
    private int status;

    //广播接收器
    private StatusChangedReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_musicplayer);
        gestureDetector = new GestureDetector(this,this);
        checkPermission();
    }

    @Override
    protected void onResume() {
        super.onResume();
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
        PropertyBean property = new PropertyBean(musicplayer.this);
        String theme = property.getTheme();
        //设置界面主题
        setTheme(theme);
        audio_Control();
        //睡眠模式打开时显示图标
        if(sleepmode==musicplayer.ISSLEEP)
            iv_sleep.setVisibility(View.VISIBLE);
        else
            iv_sleep.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void onDestroy() {
        if (status == MusicService.STATUS_STOPPED) {
            stopService(new Intent(this, MusicService.class));
        }
        super.onDestroy();
    }

    /**绑定广播接收器*/
    private void bindStatusChangedReceiver() {
        receiver = new StatusChangedReceiver();
        IntentFilter filter = new IntentFilter(MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver,filter);
    }

    //检查权限
    private void checkPermission(){
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)){
                //当拒绝了授权后，为提升用户体验，可以以弹窗的方式引导用户到设置中去进行设置
                new AlertDialog.Builder(musicplayer.this)
                        .setMessage("需要开启权限才能正常使用")
                        .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //引导用户到设置中去进行设置
                                Intent intent = new Intent();
                                intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                                intent.setData(Uri.fromParts("package", getPackageName(), null));
                                startActivity(intent);
                            }
                        })
                        .setNegativeButton("取消", null)
                        .create()
                        .show();
            }else{
                //没有授权
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUESTCODE);
            }
        }else{
            //已经授权
            findViews();
            registerListeners();
            initMusicList();
            initListView();
            checkMusicfile();
            duration = 0;
            time = 0;
            //绑定广播接收器，可以接收广播
            bindStatusChangedReceiver();
            initSeekBarHandler();
            startService(new Intent(this, MusicService.class));
            status = MusicService.COMMAND_STOP;
            //默认播放模式是列表播放
            playmode = MODE_LIST_SEQUENCE;
            //默认睡眠模式为关闭
            sleepmode = musicplayer.NOTSLEEP;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUESTCODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //用户点击了同意授权
                    findViews();
                    registerListeners();
                    initMusicList();
                    initListView();
                    checkMusicfile();
                    duration = 0;
                    time = 0;
                    //绑定广播接收器，可以接收广播
                    bindStatusChangedReceiver();
                    initSeekBarHandler();
                    startService(new Intent(this, MusicService.class));
                    status = MusicService.COMMAND_STOP;
                    //默认播放模式是列表播放
                    playmode = MODE_LIST_SEQUENCE;
                } else {
                    //用户拒绝了授权
                    //ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUESTCODE);
                    Toast.makeText(this, "权限被拒绝无法使用", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    /** 获取显示组件 */
    private void findViews() {
        imgBtn_Previous = (ImageButton) findViewById(R.id.imageButton1);
        imgBtn_PlayOrPause = (ImageButton) findViewById(R.id.imageButton2);
        imgBtn_Stop = (ImageButton) findViewById(R.id.imageButton3);
        imgBtn_Next = (ImageButton) findViewById(R.id.imageButton4);
        list = (ListView) findViewById(R.id.listView1);
        root_Layout=(RelativeLayout)findViewById(R.id.relativeLayout1);
        playingmsm1 = (TextView)findViewById(R.id.textView);
        playingmsm2 = (TextView)findViewById(R.id.textView3);
        seekBar = (SeekBar)findViewById(R.id.seekBar1);
        text_Current = (TextView)findViewById(R.id.textView1);
        text_Duration = (TextView)findViewById(R.id.textView2);
        seekBar_vol = (SeekBar)findViewById(R.id.volumeBar);
        iv_sleep = (ImageView)findViewById(R.id.main_sleep);
    }
    /**初始化音乐列表对象*/
    private void initMusicList() {
        musicArrayList = MusicList.getMusicList();
        //避免重复添加音乐
        if(musicArrayList.isEmpty())
        {
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[] {
                            MediaStore.Audio.Media.TITLE,
                            MediaStore.Audio.Media.DURATION,
                            MediaStore.Audio.Media.ALBUM,
                            MediaStore.Audio.Media.ARTIST,
                            MediaStore.Audio.Media._ID,
                            MediaStore.Audio.Media.DATA,
                            MediaStore.Audio.Media.DISPLAY_NAME }, null, null,
                    MediaStore.Audio.AudioColumns.TITLE);


            //标题
            int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
            //艺术家
            int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
            //总时长
            int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
            //路径
            int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
            //专辑
            int indexAlbum = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ALBUM);

            /**通过mMusicCursor游标遍历数据库，并将Music类对象加载带ArrayList中*/
            for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor
                    .moveToNext()) {
                String strTitle = mMusicCursor.getString(indexTitle);
                String strArtist = mMusicCursor.getString(indexArtist);
                String strTotoalTime = mMusicCursor.getString(indexTotalTime);
                String strPath = mMusicCursor.getString(indexPath);
                String strAlbum = mMusicCursor.getString(indexAlbum);

                if (strArtist.equals("<unknown>"))
                    strArtist = "无艺术家";
                Music music = new Music(strTitle, strArtist, strPath, strTotoalTime,strAlbum);
                musicArrayList.add(music);
            }
        }
    }
    /**设置适配器并初始化listView*/
    private void initListView() {
        List<Map<String, String>> list_map = new ArrayList<Map<String, String>>();
        HashMap<String, String> map;
        SimpleAdapter simpleAdapter;
        for (Music music : musicArrayList) {
            map = new HashMap<String, String>();
            map.put("musicName", music.getMusicName());
            map.put("musicArtist", music.getMusicArtist());
            list_map.add(map);
        }

        String[] from = new String[] { "musicName", "musicArtist" };
        int[] to = { R.id.listview_tv_titele_item, R.id.listview_tv_artist_item };

        simpleAdapter = new SimpleAdapter(this, list_map, R.layout.listview,from, to);
        list.setAdapter(simpleAdapter);
    }

    /**如果列表没有歌曲，则播放按钮不可用，并提醒用户*/
    private void checkMusicfile()
    {
        if (musicArrayList.isEmpty()) {
            imgBtn_Next.setEnabled(false);
            imgBtn_PlayOrPause.setEnabled(false);
            imgBtn_Previous.setEnabled(false);
            imgBtn_Stop.setEnabled(false);
            Toast.makeText(getApplicationContext(), "当前没有歌曲文件",Toast.LENGTH_SHORT).show();
        } else {
            imgBtn_Next.setEnabled(true);
            imgBtn_PlayOrPause.setEnabled(true);
            imgBtn_Previous.setEnabled(true);
            imgBtn_Stop.setEnabled(true);
        }
    }

    // 媒体播放类
    private MediaPlayer player = new MediaPlayer();

    /** 为显示组件注册监听器 */
    private void registerListeners() {

        imgBtn_Previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //moveNumberToPrevious();
                //play(number);
                //imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
                switch (playmode){
                    case MODE_RANDOM_PLAY:
                        sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
                        break;
                    default:
                        sendBroadcastOnCommand(MusicService.COMMAND_PREVIOUS);
                        break;
                }
            }
        });
        imgBtn_PlayOrPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (player != null && player.isPlaying()) {
//                    pause();
//                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
//                } else {
//                    play(number);
//                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
//                }
                switch (status) {
                    case MusicService.STATUS_PLAYING:
                        sendBroadcastOnCommand(MusicService.COMMAND_PAUSE);
                        break;
                    case MusicService.STATUS_PAUSED:
                        sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        break;
                    case MusicService.COMMAND_STOP:
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        break;
                    default:
                        break;
                }
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if(status == MusicService.STATUS_PLAYING){
                    text_Current.setText(formatTime(seekBar.getProgress()));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                gesturefree = false;
                seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                gesturefree = true;
                if(status != MusicService.STATUS_STOPPED){
                    time = seekBar.getProgress();
                    text_Current.setText(formatTime(time));
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                }
                if(status == MusicService.STATUS_PLAYING){
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }
                if(status == MusicService.STATUS_PAUSED){
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }
            }
        });

        imgBtn_Stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                stop();
//                imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
                sendBroadcastOnCommand(MusicService.COMMAND_STOP);
            }
        });
        imgBtn_Next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                moveNumberToNext();
//                play(number);
//                imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
                switch (playmode){
                    case MODE_RANDOM_PLAY:
                        sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
                        break;
                    default:
                        sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                        break;
                }
            }
        });
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                number=position;
//                play(number);
//                imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
            }
        });


    }



    /**发送命令，控制音乐播放*/
    private void sendBroadcastOnCommand(int command) {
        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);
        //根据不同命令，封装不同的数据
        switch (command) {
            case MusicService.COMMAND_PLAY:
                intent.putExtra("number", number);
                break;
            case MusicService.COMMAND_SEEK_TO:
                intent.putExtra("time",time);
                break;
            case MusicService.COMMAND_PREVIOUS:
            case MusicService.COMMAND_NEXT:
            case MusicService.COMMAND_PAUSE:
            case MusicService.COMMAND_RESUME:
            case MusicService.COMMAND_STOP:
            default:
                break;
        }

        sendBroadcast(intent);
    }

    /**
     * 函数名：状态接收器
     * 功能：
     **/
    class StatusChangedReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String musicName = intent.getStringExtra("musicName");
            String musicArtist = intent.getStringExtra("musicArtist");
            String album = intent.getStringExtra("album");
            status = intent.getIntExtra("status", -1);
            switch (status) {
                case MusicService.STATUS_PLAYING:
                    //musicplayer.this.setTitle("正在播放："+musicName + "-" + musicArtist);
                    seekBarHandler.removeMessages(PROGRESS_INCREASE);
                    time = intent.getIntExtra("time",0);
                    Log.e("servicetime",formatTime(time));
                    duration = intent.getIntExtra("duration",0);
                    number = intent.getIntExtra("number",number);
                    list.setSelection(number);
                    seekBar.setProgress(time);
                    seekBar.setMax(duration);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,0);
                    text_Duration.setText(formatTime(duration));
                    playingmsm1.setText(musicName);
                    playingmsm2.setText(musicArtist + "—" +album);
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.pause);
                    break;
                case MusicService.STATUS_PAUSED:
                    //musicplayer.this.setTitle("正在播放："+musicName + "-" + musicArtist);
                    seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
                    playingmsm1.setText(musicName);
                    playingmsm2.setText(musicArtist + "—" +album);
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    break;
                case MusicService.STATUS_STOPPED:
                    //musicplayer.this.setTitle("");
                    time=0;
                    duration=0;
                    text_Duration.setText(formatTime(duration));
                    text_Current.setText(formatTime(time));
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    playingmsm1.setText("未在播放");
                    playingmsm2.setText("");
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    break;
                case MusicService.STATUS_COMPLETED:
                    number = intent.getIntExtra("number",0);
                    //顺序播放
                    if(playmode == musicplayer.MODE_LIST_SEQUENCE)
                    {
                        if(number == MusicList.getMusicList().size() - 1) {
                            sendBroadcastOnCommand(MusicService.STATUS_STOPPED);
                        }else{
                            sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                        }
                    }
                    //单曲循环
                    else if(playmode == musicplayer.MODE_SINGLE_CYCLE)
                    {
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    }
                    //循环列表
                    else if(playmode == musicplayer.MODE_LIST_CYCLE)
                    {
                        if(number == MusicList.getMusicList().size()-1){
                            number=0;
                            sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        }else{
                            sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                        }
                    }
                    //随机播放
                    else if(playmode == musicplayer.MODE_RANDOM_PLAY)
                    {
                        sendBroadcastOnCommand(MusicService.COMMAND_RANDOM);
                    }
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    musicplayer.this.setTitle("");
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 函数名：setTheme
     * 功能：播放器设定主题
     **/
    private void setTheme(String theme){
        if("彩色".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.bg_color);
        }else if("花朵".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_digit_flower);
        }else if("磨砂".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_mountain);
        }else if("森林".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_running_dog);
        }else if("冰雪".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_snow);
        }else if("女孩".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_music_girl);
        }else if("霓虹灯".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.bg_blur);
        }
    }

    /**
     * 函数名：onCreateOptionsMenu
     * 功能：创建OptionMenu
     * */
    public boolean onCreateOptionsMenu(Menu menu){
        this.getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }

    /**
     *函数名：onOptionsItemSelected
     *功能：提供选择
     *      1、更换主题
     *      2、播放模式
     *      3、睡眠设置
     *      4、关于我们
     *      5、退出
     * */
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()){
            case R.id.menu_theme:
                new AlertDialog.Builder(this)
                        .setTitle("请设置主题").
                        setItems(R.array.theme,
                                new android.content.DialogInterface.OnClickListener(){
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        String theme = PropertyBean.THEMES[i];
                                        musicplayer.this.setTheme(theme);
                                        PropertyBean property =new PropertyBean(musicplayer.this);
                                        property.setAndSaveTheme(theme);
                                    }
                                }).show();
                                break;
            case R.id.menu_about:
                new AlertDialog.Builder(musicplayer.this)
                        .setTitle("关于我们").
                        setMessage(R.string.about2).show();
                break;
            case R.id.menu_quit:
                new AlertDialog.Builder(this)
                        .setTitle("提醒").
                        setMessage(R.string.quit_message).setPositiveButton("确定",new android.content.DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                System.exit(0);
                            }
                        }).setNegativeButton("取消",new android.content.DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).show();
                break;
            case R.id.menu_playmode:
                String[] mode = new String[] {"顺序播放","单曲循环","列表循环","随机播放"};
                AlertDialog.Builder builder = new AlertDialog.Builder(musicplayer.this);
                builder.setTitle("播放模式");
                builder.setSingleChoiceItems(mode, playmode,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                           playmode = i;
                            }
                        });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        switch (playmode){
                            case 0:
                                playmode = musicplayer.MODE_LIST_SEQUENCE;
                                Toast.makeText(getApplicationContext(),R.string.sequence,Toast.LENGTH_SHORT);
                                break;
                            case 1:
                                playmode = musicplayer.MODE_SINGLE_CYCLE;
                                Toast.makeText(getApplicationContext(),R.string.singlecycle,Toast.LENGTH_SHORT);
                                break;
                            case 2:
                                playmode = musicplayer.MODE_LIST_CYCLE;
                                Toast.makeText(getApplicationContext(),R.string.listcycle,Toast.LENGTH_SHORT);
                                break;
                            case 3:
                                Toast.makeText(getApplicationContext(),R.string.randomplay,Toast.LENGTH_SHORT);
                                break;
                            default:
                                break;
                        }
                    }
                });
                builder.create().show();
                break;
            case R.id.menu_sleep:
                showSleppDialog();
                break;
            case R.id.menu_lrc:
                Intent intent = new Intent(musicplayer.this,LrcActivity.class);
                startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 函数名：formatTime
     * 功能：设置当前时间和时间总长的格式
     * */
    private String formatTime(int msec){
        int minute = msec / 1000 / 60;
        int second = msec / 1000 % 60;
        String minuteString;
        String secondString;
        if(minute < 10){
            minuteString = "0" + minute;
        }else{
            minuteString = "" + minute;
        }
        if(second < 10){
            secondString = "0" + second;
        }else{
            secondString = "" + second;
        }
        return minuteString + ":" + secondString;
    }

    private void initSeekBarHandler(){
        seekBarHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case PROGRESS_INCREASE:
                        if(seekBar.getProgress() <duration){
                            //进度条前进一秒
                            seekBar.setProgress(time);
                            //seekBar.incrementProgressBy(1000);
                           seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                            //修改当前时间
                            text_Current.setText(formatTime(time));
                            time += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        //按住进度条时，消去增加的进度
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        //当更换歌曲时，重置进度条
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(0);
                        text_Current.setText("00:00");
                        break;
                }
            }
        };
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int progress;
       switch (keyCode)
       {
           case KeyEvent.KEYCODE_BACK:
               exitByDoubleClick();
               break;
           case KeyEvent.KEYCODE_VOLUME_UP:
               progress = seekBar_vol.getProgress();
               if(progress != seekBar_vol.getMax()){
                   seekBar_vol.setProgress(progress+1);
               }
               break;
           case KeyEvent.KEYCODE_VOLUME_DOWN:
               progress = seekBar_vol.getProgress();
               if(progress != 0){
                   seekBar_vol.setProgress(progress-1);
               }
               break;

       }
       return false;
    }

    private void exitByDoubleClick(){
        Timer timer = null;
        if(ExitFlag == false)
        {
            ExitFlag = true;
            Toast.makeText(this,"按多一次退出程序",Toast.LENGTH_SHORT).show();
            timer = new Timer();
            timer.schedule(new TimerTask(){
                @Override
                public void run() {
                    ExitFlag = false;
                }},2000);
        }
        else
        {
            System.exit(0);
        }
    }

    /**
     * 函数名：audio_Control
     * 功能：
     * */
    private void audio_Control(){
        //获取音量管理
        final AudioManager audioManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
        //调整的当前音量是媒体音量，避免涉及系统音量的误操作
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        //设置滑动最大值
        final int max_volume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        seekBar_vol.setMax(max_volume);
        //获取当前音量
        final int presentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekBar_vol.setProgress(presentVolume);
        /**
         * 这里需要填充改变音量后提示的音量值
         * */
        seekBar_vol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                STR = i;
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,i,AudioManager.FLAG_PLAY_SOUND);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //提示当前的音量值
                Toast toast = Toast.makeText(getApplicationContext(),"音量值:"+(STR*100/max_volume)+"%",Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER,0,0);
                LinearLayout toastView = (LinearLayout)toast.getView();
                ImageView imageVolume = new ImageView(getApplicationContext());
                imageVolume.setImageResource(R.drawable.voicegai);
                toastView.addView(imageVolume,0);
                toast.show();
            }
        });
    }

    /**
     * 函数：showSleppDialog
     * 功能：
     * */
    private void showSleppDialog()
    {
        //用getLayoutInflater获取自定义的布局，然后初始化View对象
        final View userView = this.getLayoutInflater().inflate(R.layout.dialog,null);

        //绑定组件
        final TextView tv_minute = (TextView)userView.findViewById(R.id.dialog_tv);
        final Switch switch1 = (Switch)userView.findViewById(R.id.dialog_switch);
        final SeekBar seekBar2 = (SeekBar)userView.findViewById(R.id.dialog_seekbar);

        tv_minute.setText("睡眠于"+sleepminute+"分钟");
        //通过当前的睡眠模式更改Switch的状态
        if(sleepmode == musicplayer.ISSLEEP) switch1.setChecked(true);
        seekBar2.setMax(60);
        seekBar2.setProgress(sleepminute);
        //监听SeekBar的动作从而对睡眠时间进行设定
        seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                sleepminute = i;
                tv_minute.setText("睡眠于"+ sleepminute +"分钟");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                sleepmode = b;
            }
        });
        //设置定时器任务，到达规定时间就退出软件
        final TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.exit(0);
            }
        };
        //定义对话框以及初始化
        final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("选择睡眠时间(0-60)");
        dialog.setView(userView);
        //设置取消按钮
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        //设置重置时间
        dialog.setNeutralButton("重置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if(sleepmode == musicplayer.ISSLEEP)
                {
                    timerTask.cancel();
                    timer_sleep.cancel();
                }
                sleepmode = musicplayer.NOTSLEEP;
                sleepminute = 20;
                //睡眠图标设置不可见
                iv_sleep.setVisibility(View.INVISIBLE);
            }
        });
        //设置确认按钮
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if(sleepmode == ISSLEEP)
                {
                    timer_sleep = new Timer();
                    int time = seekBar2.getProgress();
                    timer_sleep.schedule(timerTask,time*60*1000);
                    iv_sleep.setVisibility(View.VISIBLE);
                }
                else
                {
                    timerTask.cancel();
                    if(timer_sleep != null) timer_sleep.cancel();
                    dialogInterface.dismiss();
                    iv_sleep.setVisibility(View.INVISIBLE);
                }
            }
        });
        dialog.show();
    }

    /**
     * 函数：onTouchEvent
     * 功能：
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

    /**
     * 函数：onFling
     * 功能:
     */
    @Override
    public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        if((motionEvent1.getX() - motionEvent.getX() > 150) && gesturefree == true)
        {
            //如果滑动超过150像素点，则实现Activity的跳转
            Intent intent = new Intent();
            intent.setClass(musicplayer.this,LrcActivity.class);
            startActivity(intent);
            //动画优化
            overridePendingTransition(R.anim.to_right_enter,R.anim.to_right_exit);
            Toast.makeText(getApplicationContext(),"歌词",Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {

    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        return false;
    }

    @Override
    public boolean onDown(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(gestureDetector.onTouchEvent(ev))
        {
            ev.setAction(MotionEvent.ACTION_CANCEL);
        }
        return super.dispatchTouchEvent(ev);
    }
}
